import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Cart from '../views/Cart'
import Info from '../views/Info'
import OrderDetail from '../views/OrderDetail'
import Pay from '../views/Pay'
import Order from '../views/Order'
import Login from '../views/Login'
import Mine from '../views/Mine'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
    },
    {
        path: '/cart',
        name: 'Cart',
        component: Cart
    },
    {
        path: '/info',
        name: 'Info',
        component: Info
    },
    {
        path: '/orderDetail',
        name: 'OrderDetail',
        component: OrderDetail
    },
    {
        path: '/pay',
        name: 'Pay',
        component: Pay
    },
    {
        path: '/order',
        name: 'Order',
        component: Order
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/mine',
        name: 'Mine',
        component: Mine
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

// 每个页面的登录状态验证
router.beforeEach((to, from, next) => {
    if (to.path.startsWith('/login')) {
        // localStorage中移除user
        window.localStorage.removeItem('user')
        next()
    } else {
        let user = JSON.parse(window.localStorage.getItem('user'))
        if (!user) {
            // 跳转到/login
            next({path: '/login'})
        } else {
            // 跳转到本来要去的页面
            next()
        }
    }
})

export default router
